package com.nine.gxh.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: duonine
 * @date: 2023/7/14
 */
@Component
public class DictTypeConverter implements Converter<String> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    // 将文本转为数据库值
    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String label = cellData.getStringValue();
        ISysDictDataService dictDataService = SpringUtils.getBean(ISysDictDataService.class);
        // 根据数据字典和文本，获取到实际的值
        String value = dictDataService.selectDictValue("gxh_channel_type", label);
        return value;
    }

    // 将数据库值转为文本
    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        ISysDictDataService dictDataService = SpringUtils.getBean(ISysDictDataService.class);
        String label = dictDataService.selectDictLabel("gxh_channel_type", value);
        return new WriteCellData<>(label);
    }
}
